<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
defined('BY_JYA') or exit('error');
if(!$_SESSION['isfounder']){
	exi('无权访问！','error','core/account.siteinfo/');
}
$_RQ['op']=$_RQ['op']?$_RQ['op']:'get';
$return=array();
if($_RQ['op']=='get'){
	if(!$_RQ['name']){
		exi('请选择应用！','error','goback');
	}
	$app=pdo_get('core_plugins',array('name'=>$_RQ['name']),array('title','name','version','release','cloud_id'));
	$cloud_ids=$app['cloud_id'];
	if($cloud_ids){
		$post=array('cloud_ids'=>$cloud_ids);
		$versions=cloud_request('update.plugin.getup',$post,'','',30);
	}
	$newlist=array();
	foreach($versions as $name=>$version){
			if(!$version['release'] || $version['release']==$app['release']){
			}else{
				$app['new_version']=$version['version'];
				$app['sys_version']=$version['sys_version'];
				$app['v_desc']=$version['v_desc'];
			}
	}
	$return['item']=$app;
	if($app['new_version']){
		$return['htmls']=array(
			'type'=>'edit',
			'post'=>'update',
			'desc'=>'更新版本',
			'edit'=>array(
				array('name'=>'title','title'=>'插件名称','type'=>'copy'),
				array('name'=>'version','title'=>'当前版本','type'=>'copy'),
				array('name'=>'v_desc','title'=>'最新更新说明','type'=>'copy'),
				array('name'=>'sys_version','title'=>'最低系统版本支持','type'=>'copy'),
				array('name'=>'new_version','title'=>'一键更新到最新版本','type'=>'copy'),
			),
		);
	}else{
		$return['htmls']=array(
			'type'=>'look',
			'desc'=>'无需更新',
			'look'=>array(
				array('name'=>'title','title'=>'插件名称','type'=>'string'),
				array('name'=>'version','title'=>'当前版本','type'=>'string'),
			),
		);
	}
	exi($return);
}
if($_RQ['op'] == 'update') {
	//更新插件
	$plugin=get_postdata();
	$id=intval($_RQ['id']);
	$version=core_setting('version');
	$sys_version=$plugin['sys_version'];
	if($sys_version && version_compare($version['version'], $sys_version) == -1) {
		exi('系统版本需要V-'.$sys_version.'以上，请先更新系统框架！','error');
	}
	$dir = ROOT_PLUGIN. $plugin['name'];
	if(!$_SESSION['download'] || !is_file(ROOT_AT.$plugin['name'].'.update')){
		$post=array('cloud_id'=>$plugin['cloud_id']);
		//查找插件现有数据结构
		if($plugin['type']==4){
			//联盟插件插件
			$tables=pdo_getcolumn('core_old_plugins',array('name'=>$plugin['name']),'tables');
			$tables=explode(';',trim($tables,';'));
		}else{
			$tables=pdo_fetchall("SHOW TABLES LIKE '".TABLE_PRE.$plugin['name']."\_%'");
			if($tables){
				foreach($tables as &$row){
					$row=array_shift($row);
					$row=explode('_',$row,2);
					$row=$row['1'];
				}
			}
		}
		//读取插件数据结构
		$sqls=array();
		if($tables){
			foreach($tables as $table){
				if(!$table){
					continue;
				}
				$tablename=TABLE_PRE.$table;
				$sql=pdo_fetch('show create table '.$tablename);
				$sqls[$table]=$sql['Create Table'];
			}
		}
		$post['sqls']=$sqls;
		$post['release']=$plugin['release'];
		if($api_id){
			$dat=api_request('api_shop.update.plugin.build',$api_id,$post);
		}else{
			$dat=cloud_request('update.plugin.build',$post,'','',50);
		}
		if(!$dat['plugin']){
			exi('更新失败，获取插件异常，请排查防火墙拦截或联系市场客服！','error');
		}
		//更新文件
		$upfiles=$files = array();
		if(!empty($dat['files'])) {
			$mdir=ROOT_AT .'module_baks/'.$plugin['name'];
			if(!is_dir($mdir)){
				cfc('files')->mkdirs($mdir);
			}
			$bak = $mdir.'/'.$plugin['version'].'.'.TIMESTAMP;
			$zip= new ZipArchive();
			$zip->open($bak, ZipArchive::CREATE);
			foreach($dat['files'] as $file) {
				$entry = $dir . $file['path'];
				if(!is_file($entry) || md5_file($entry) != $file['checksum']) {
					$files[] =$file['path'];
					$upfiles[]=$file;
				}
				if(is_file($entry) && md5_file($entry) != $file['checksum']) {
					$zip->addFile($entry,$file['path']);
				}
			}
			$zip->close();
		}
		//检查文件权限
		if(!empty($files)){
			$error=array();
			foreach($files as $f){
				$path = ROOT_PLUGIN.$plugin['name'].$f;
				if(file_exists($path)){
					if(!is_writable($path)){
					 $error[]=$path.'文件没有写入的权限';
					}
				}else{
					$path=get_dirname($path);
					if(!is_writable($path)){
					$error[]=$path.'文件夹没有写入的权限';
					}
				}
			}
			if($error){
				$error=implode(';',$error);
				exi($error,'error');
			}
		}
	
		if(!empty($files)){
			$post=array('cloud_id'=>$plugin['cloud_id'],'files'=>$files,'new'=>1);
			if($api_id){
				$files=api_request('api_shop.update.plugin.getmodule',$api_id,$post);
			}else{
				$files=cloud_request('update.plugin.getmodule',$post,'','',50);
			}
			//下载更新文件时，如果内容较少，则一次性下载之，否则跳转下载页分批下载
			if($files['parts']==1){
				if($api_id){
					$data=api_request('api_shop.update.download',$api_id,array('id'=>$files['id'],'part'=>1),true);
				}else{
					$data=cloud_request('update.download',array('id'=>$files['id'],'part'=>1),true,'',60);
				}
				file_put_contents(ROOT_AT.$plugin['name'].'.update',$data);
			}else{
				$_SESSION['download']=array(
					'id'=>$files['id'],
					'parts'=>$files['parts'],
					'to'=>$plugin['name'].'.update',
					'back'=>'core/cloud.app_update//name='.$plugin['name'],
				);
				$dat=serialize($dat);file_put_contents(ROOT_AT.$plugin['name'].'.update_data',$dat);
				exi('准备下载更新文件！','success','core/cloud.download/');
			}
		}
	}
	if(is_file(ROOT_AT.$plugin['name'].'.update')){
		$zip = new ZipArchive();
		$zip->open(ROOT_AT.$plugin['name'].'.update');
		$zip->extractTo($dir);
		$zip->close();
		@unlink(ROOT_AT.$plugin['name'].'.update');
		
	}
	if($_SESSION['download']){
		unset($_SESSION['download']);
	}
	if(!$dat){
		$dat=file_get_contents(ROOT_AT.$plugin['name'].'.update_data');
		if($dat){
			$dat=unserialize($dat);
		}
		@unlink(ROOT_AT.$plugin['name'].'.update_data');
	}
	//更新数据库结构
	if($dat['upsqls']){
		pdo_query($dat['upsqls']);
	}
	//执行额外操作
	if(!empty($dat['updata'])){
		foreach($dat['updata'] as $up){
			file_put_contents(ROOT_AT.'update.php',$up);
			require ROOT_AT.'update.php';
		}
	}
	@unlink(ROOT_AT.'update.php');
	//检测文件是否更新成功
	if($upfiles){
		foreach($upfiles as $file) {
			$entry = $dir . $file['path'];
			if(!is_file($entry) || md5_file($entry) != $file['checksum']) {
				exi("更新失败，请设置好模块根目录（".$dir."）的权限再更新！",'error');
			}
		}
	}
	//更新其他
	$data=array_fields(array('version','basic','style','intype','covers','menus','diypage','actionlinks','mobile_menus','release','istakeover','image','link','custom_access_type','is_legao','is_wxwork','diy_legao','msgtpl','endtime'),$dat['plugin']);
	if($data['image'] && !$plugin['image']){
		$image=file_get_contents($data['image']);
		$data['image']=cfc('files')->source_save($image,'image','jpg','插件“'.$data['title'].'”logo');
	}else{
		unset($data['image']);
	}
	$menus=model('core/module')->get_filemenus($plugin['name']);
	if(count($menus)){
		$data['menus']=ijson_encode($menus);
	}
	pdo_update('core_plugins',$data,array('id'=>$id));
	model('core/msg_tpl')->check_tpl($plugin['name']);
	if($plugin['type']==4){
		$update=array_fields(array('setting','need_menu','tables'),$dat['plugin']);
		pdo_update('core_old_plugins',$update,array('name'=>$plugin['name']));
	}
	//检测权限数据是否已添加，如果没有，则添加之
	if(!pdo_getcolumn('core_plugin_permissions',array('plugin'=>$plugin['name']),'id')){
		$permission=array(
			'type'=>1,
			'plugin'=>$plugin['name'],
			'title'=>$plugin['title'],
			'image'=>$plugin['image'],
		);
		pdo_insert('core_plugin_permissions',$permission);
	}
	//检测更新权限数据
	if($dat['plugin']['permissions']){
		foreach($dat['plugin']['permissions'] as $perm){
			$check=pdo_getcolumn('core_plugin_permissions',array('plugin'=>$dat['plugin']['name'],'action'=>$perm['action'],'op'=>$perm['op']),'id');
			if($check){
				pdo_update('core_plugin_permissions',array('type'=>$perm['type'],'title'=>$perm['title']),array('id'=>$check));
			}else{
				$new_perm=array_fields(array('type','title','action','op'),$perm);
				$new_perm['plugin']=$dat['plugin']['name'];
				pdo_insert('core_plugin_permissions',$new_perm);
			}
		}
	}
	//检测更新插件事件订阅
	if($dat['plugin']['subscribe']){
		foreach($dat['plugin']['subscribe'] as $subscribe){
			$data=array(
				'subscriber'=>$subscribe['subscriber'],
				'plugin'=>$subscribe['plugin'],
				'event'=>$subscribe['event'],
				'paixu'=>$subscribe['paixu'],
			);
			$sparams=array(
				'subscriber'=>$subscribe['subscriber'],
				'plugin'=>$subscribe['plugin'],
				'event'=>$subscribe['event']
			);
			$check=pdo_getcolumn('core_plugin_subscribe',$sparams,'id');
			if(!$check){
				pdo_insert('core_plugin_subscribe',$data);
			}else{
				pdo_update('core_plugin_subscribe',array('paixu'=>$subscribe['paixu']),array('id'=>$check));
			}
		}
	}
	//插件初始化数据
	if($dat['plugin']['install_data']){
		foreach($dat['plugin']['install_data'] as $table=>$data){
			$check=pdo_count('core_plugin_install_data',array('plugin_name'=>$dat['plugin']['name'],'table'=>$table));
			if(!$check){
				pdo_insert('core_plugin_install_data',array('plugin_name'=>$dat['plugin']['name'],'table'=>$table));
			}
			$check=pdo_count($table);
			if($check){
				continue;
			}
			foreach($data as $row){
				pdo_insert($table,$row);
			}
		}
	}
	//更新页面缓存
	core_setting('cache',array('urlargs'=>TIMESTAMP));
	exi('更新成功！','','get');
}
?>